<script>
	import {
		checkLogin
	} from "./libs/login";
	import {
		HTTP_REQUEST_URL
	} from './config/app';
	import Auth from './libs/wechat.js';
	import Routine from './libs/routine.js';
	import Apps from './libs/apps.js';
	import {
		getTheme,
		addCollect,
		delCollect,
		BusinessList,
		existsCollect,
		tophoneCoin,
		RewardCoinL,
		getKftoPhone
	} from './api/api.js';

	import {
		contactAdd
	} from "@/api/subletOfShop.js"
	import {
		mapActions
	} from 'vuex'
	import {
		spread,
		getIm,
		getUserInfo,
		addCommun,
		getFans,
		getUserFriend,
		addUserFriend,
		delUserFriend,
		getUFriendFansCount
	} from "@/api/user";
	import Cache from './utils/cache';
	import _chunkArr from '@/pages/chatroom/utils/chunkArr';
	// require("sdk/libs/strophe");
	let WebIM = (wx.WebIM = require("@/pages/chatroom/utils/WebIM")["default"]);
	let msgStorage = require("@/pages/chatroom/components/chat/msgstorage");
	let msgType = require("@/pages/chatroom/components/chat/msgtype");
	let disp = require("@/pages/chatroom/utils/broadcast");
	let logout = false;

	import {
		onGetSilentConfig
	} from '@/pages/chatroom/components/chat/pushStorage'

	let timeOut = null;


	function ack(receiveMsg) {
		// 处理未读消息回执
		var bodyId = receiveMsg.id; // 需要发送已读回执的消息id

		var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
		ackMsg.set({
			id: bodyId,
			to: receiveMsg.from,
		});
		WebIM.conn.send(ackMsg.body);
	}

	function onMessageError(err) {
		if (err.type === "error") {
			uni.showToast({
				title: err.errorText,
			});
			return false;
		}

		return true;
	}

	function getCurrentRoute() {
		let pages = getCurrentPages();
		if (pages.length > 0) {
			let currentPage = pages[pages.length - 1];
			return currentPage.route;
		}
		return "/";
	}



	// // 不包含陌生人版本(不接收陌生人消息)
	// function calcUnReadSpot(message) {
	//   let myName = uni.getStorageSync("myUsername");
	//   let members = uni.getStorageSync("member") || []; //好友

	//   var listGroups = uni.getStorageSync("listGroup") || []; //群组
	//   let allMembers = members.concat(listGroups);
	//   let count = allMembers.reduce(function(result, curMember, idx) {
	//     let chatMsgs;
	//     if (curMember.groupid) {
	//       chatMsgs =
	//         uni.getStorageSync(curMember.groupid + myName.toLowerCase()) || [];
	//     } else {
	//       chatMsgs =
	//         uni.getStorageSync(
	//           curMember.name && curMember.name.toLowerCase() + myName.toLowerCase()
	//         ) || [];
	//     }
	//     return result + chatMsgs.length;
	//   }, 0);
	//   getApp().globalData.unReadMessageNum = count;
	//   disp.fire("em.unreadspot", message);
	// }

	// 包含陌生人版本
	//该方法用以计算本地存储消息的未读总数。
	function calcUnReadSpot(message) {
		let myName = uni.getStorageSync("myUsername");
		let pushObj = uni.getStorageSync("pushStorageData")
		let pushAry = pushObj[myName] || []
		uni.getStorageInfo({
			success: function(res) {
				let storageKeys = res.keys;
				let newChatMsgKeys = [];
				let historyChatMsgKeys = [];
				storageKeys.forEach((item) => {
					if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
						newChatMsgKeys.push(item);
					}
				});
				let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
					let newName = curMember.split(myName)[0]
					let chatMsgs;
					chatMsgs = uni.getStorageSync(curMember) || [];
					//过滤消息来源与当前登录ID一致的消息，不计入总数中。
					chatMsgs = chatMsgs.filter((msg) => msg.yourname !== myName);
					if (pushAry.includes(newName)) return result
					return result + chatMsgs.length;
				}, 0);
				getApp().globalData.unReadMessageNum = count;
				disp.fire("em.unreadspot", message);
			},
		});
	}

	function saveGroups() {
		var me = this;
		return WebIM.conn.getGroup({
			limit: 50,
			success: function(res) {
				uni.setStorage({
					key: "listGroup",
					data: res.data,
				});
			},
			error: function(err) {
				
			},
		});
	}
	export default {
		globalData: {
			phoneNumber: '',
			unReadMessageNum: 0,
			userInfo: null,
			userInfoFromServer: null, //用户属性从环信服务器获取
			friendUserInfoMap: new Map(), //好友属性
			saveFriendList: [],
			saveGroupInvitedList: [],
			isIPX: false, //是否为iphone X
			spread: "",
			st: '',
			infoId:'',
			spreadType: "",
			storeCategory:'',
			isLogin: false,
			windowHeight: 0,
			navHeight: 0,
			navHeight2: 0,
			imagesCdn:'https://image.shanghepu.com/cdn/',
			navH: 0,
			id: 0,
			isToAdd: false,
			isIframe: false,
			theme: Cache.get('theme') || 'theme1',
			async toPhone(phone, mind, {
				open,
				infoCity,
				infoId,
				statusPhone,
				type,
				storeCategory
			}) {
				let that = this;
				if (mind == 1 || statusPhone == 1) {
					uni.showModal({
						title: '提示',
						content: '是否拨打电话',
						success(res) {
							if (res.confirm) {
								uni.makePhoneCall({
									phoneNumber: phone
								});

							}
							
						}
					})
					return;
				}
				//如果没有公开
				if (!open) {
					
					let result = await getKftoPhone({
						city: infoCity
					})
					
					uni.showModal({
						title: '提示',
						content: '当前用户信息设置为隐私,请在线咨询或拨打客服电话' + (result.data ? ('(' + result.data + ')') : '') +
							'。是否立即拨打',
						success(res) {
							if (res.confirm) {
								if (!result.data) {
									uni.showToast({
										title: '当前城市未开通',
										icon: 'none',
										duration: 1500
									});
									return;
								}
								uni.makePhoneCall({
									phoneNumber: result.data
								});
							}
							
						}
					})
					return;
				}

				let result = await RewardCoinL();
				if (result.data.userCoin && (result.data.userCoin - result.data.coin) > 0) {
					uni.showModal({
						title: '提示',
						content: '是否查看并拨打电话(需扣除' + result.data.coin + '个金币，剩余' + result.data.userCoin + '个)',
						success(res) {
							if (res.confirm) {
								tophoneCoin({
									infoId:infoId?infoId:'',
									type:type||type==0?type:'',
									phone,
									storeCategory:storeCategory?storeCategory:''
									
								}).then(r => {
									if (r.code == 200) {
										uni.makePhoneCall({
											phoneNumber: phone
										});
									} else {
										if(e.indexOf('金币不足')){
											uni.navigateTo({
												url:'/pages/aboutUsers/userGoldcoin/userGoldcoin'
											})
										}else{
											uni.showToast({
												title: e,
												icon: "none"
											})
										}
									}
								}).catch(e => {
									if(e.indexOf('金币不足')){
										uni.navigateTo({
											url:'/pages/aboutUsers/userGoldcoin/userGoldcoin'
										})
									}else{
										uni.showToast({
											title: e,
											icon: "none"
										})
									}
								})

							}
							
						}
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '需扣除' + result.data.coin + '个金币,金币不足,是否立即充值',
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url:'/pages/aboutUsers/userGoldcoin/userGoldcoin'
								})
							}
						}
					})
				}




			},
			conn: {
				closed: false,
				curOpenOpt: {},

				open(opt) {
					uni.showLoading({
						title: "正在初始化客户端..",
						mask: true,
					});
					this.curOpenOpt = opt;
					WebIM.conn.open(opt).then(() => {
						//token获取成功，即可开始请求用户属性。
						disp.fire("em.mian.profile.update");
						disp.fire("em.mian.friendProfile.update");
					}).catch((err) => {
						
					});
					this.closed = false;
				},

				reopen() {
					if (this.closed) {
						//this.open(this.curOpenOpt);
						WebIM.conn.open(this.curOpenOpt);
						this.closed = false;
					}
				},
			},
			//发布编辑详情处理
			ft(ids, names) {
				if (!ids || !names) {
					return '';
				}
				names = names.split('/')
				return ids.split(',').map((item, index) => ({
					id: item,
					describe: names[index],
					name: names[index]
				}))
			},
			//发布编辑详情处理
			fp(list, key, value) {

				if (!list) {
					return {}
				}
				list.forEach((item, ind) => {
					if (item[key] == value) {
						item.index = ind
					}
				})
				return list.filter(item => item[key] == value)[0]
			},
			//一个字段判断多个值
			isNullFiled(filed, value, value1) {
				return filed && filed !== 'false' ? value : value1;
			},
			//两个值 哪个有值选哪个
			isChooseFile(filed1, filed2, msg) {
				if (filed1) {
					return filed1
				} else if (filed2) {
					return filed2
				} else {
					return msg
				}
			},
			//发布的参数处理
			fbDeal(d, that) {
				let notFiled = ['contacts', 'storeAdvantage', 'floor', 'shopfrontPhoto', 'renovation', 'linLuType']
				for (let k in that.dataform) {
					if (that.hasOwnProperty(k)) {
						if (notFiled.indexOf(k) == -1) {
							that[k] = that.dataform[k]
						}
					}
				}

				if (that.dataform.address) {
					that.dataform.addres = that.dataform.address
					that.addres = that.dataform.address
				}
				if (that.dataform.area) {
					that.dataform.avea = that.dataform.area
				}
				if (that.dataform.contacts && that.dataform.contacts.length > 0) {
					let contactList = that.dataform.contacts.map(item => ({
						...item,
						username: item.contactName,
						phone: item.contactPhone,
						id: item.contactId,
						infoId: item.id,
						type: item.contactType
					}))
					that.contactList = contactList.filter(item => item.duiWai != 1);
					delete that.dataform.contacts
				}

				if (that.dataform.floor) {
					that.dataform.floor = that.dataform.floor.split('-')
				}
				if (d.area) {

					that.area1 = d.area.split('-')[0]
					that.area2 = d.area.split('-')[1]
				}
				if (d.rent) {
					that.rent1 = d.rent.split('-')[0]
					that.rent2 = d.rent.split('-')[1]
				}


				if (d.renovation) {
					
					that.renovationName = this.fp(that.renovationList, 'id', d.renovation).name
				}
				if (d.linLuType) {
					that.linLuType = this.ft(d.linLuType, d.linLuTypeName)
					that.linLuTypeName = d.linLuTypeName
				}
				if (d.roadCondition) {
					that.roadCondition = this.ft(d.roadCondition, d.roadConditionName)
				}
				if (d.supportingFacility) {
					that.sspre = this.ft(d.supportingFacility, d.supportingFacilityName)
					that.supportingFacility = that.dataform.supportingFacility
				}
				if (that.dataform.sspre) {
					that.sspre = this.ft(that.dataform.sspre, that.dataform.sspreName)
				}
				if (that.dataform.hopeArea) {
					that.regionName = that.dataform.hopeAreaName
				}
				if (that.dataform.categoryId) {
					that.categoryName = that.dataform.categoryId
				}
				if (d.dianzhao) {
					that.dianzhao1 = d.dianzhao.split('-')[0]
					that.dianzhao2 = d.dianzhao.split('-')[1]
				}
				if (d.groupCurrent) {
					that.groupCurrentName = that.dataform.groupCurrentName
				}
				if (d.workingGroup) {
					that.workingGroupName = that.dataform.workingGroupName
				}
				that.dataform.storeAdvantage && that.dataform.storeAdvantage.split('/').forEach((item, index) => {
					if (that.advantages) {
						let ind = that.advantages.indexOf(item);
						if (ind == -1) {
							that.advantages.push(item)
							that.storeAdvantage.push(item)
							that.advantageIds.push(that.advantages.length - 1)
						} else {
							that.advantageIds.push(ind)
							that.storeAdvantage.push(that.advantages[ind])
						}
					}

				})
				that.dataform.shopfrontPhoto && (that.shopfrontPhotoList = that.dataform.shopfrontPhoto.split(','))
				if (d.isFace) {
					that.isFace = d.isFace == 'false' ? false : d.isFace
				}
				if (d.isSell) {
					that.isSell = d.isSell == 'false' ? false : d.isSell
				}
				if (d.transferStatus) {
					that.transferStatus = d.transferStatus == 'false' ? false : d.transferStatus
				}
				if (d.expectedRegion) {
					that.hopeArea = d.expectedRegion;
				}
				if (d.expectedRegionName) {
					that.regionName = d.expectedRegionName;
				}
				if (d.contractImage) {
					that.contractImageList = d.contractImage.split(',')
				}
				if (d.managementModel) {
					that.managementModelIndex = this.fp(that.managementModelList, 'id', d.managementModel).index
				}
				if (d.shopFrontType) {
					that.shopFrontTypeIndex = this.fp(that.shopFrontTypeList, 'id', d.shopFrontType).index
				}
				if (d.estateName) {
					that.estate = d.estateName
				}
				if (d.credentials) {
					that.credentials = d.credentials
					that.credentialsName = d.credentialsName
					that.credentialsIndex = this.fp(that.credentialsList, 'id', d.credentials).index
				}
				if (d.storefrontType) {
					that.storefrontTypeList = d.storefrontType
					that.storefrontType = d.storefrontType
					that.storefrontTypeName = d.storefrontTypeName
				}
				if ((d.latitude || d.longitude) && that.location) {
					that.location.latitude = d.latitude
					that.location.longitude = d.longitude
				}
				// if(d.projectId){
				// 	that.projectName = d.projectname
				// }
			},
			//获取商圈
			getBusinessList(location) {
				return new Promise((reslove, reject) => {
					BusinessList(location).then(res => reslove(res)).catch(e => reject(e));
				})
			},
			// 单聊
			into_singleChatRoom: function(contact) {
				var my = uni.getStorageSync("myUsername");
				var nameList = {
					myName: my,
					your: contact.phone,
					info: contact.info ? contact.info : "",
					nickname: contact.nickname
				};
				const friendUserInfoMap = getApp().globalData.friendUserInfoMap;
				
				if (friendUserInfoMap.has(nameList.your) && friendUserInfoMap.get(nameList.your)?.nickname) {
					nameList.yourNickName = friendUserInfoMap.get(nameList.your).nickname;
				}
				
				uni.navigateTo({
					url: "/pages/chatroom/chatroom?username=" + JSON.stringify(nameList),
					error(e) {
						
					},
					success() {
						addCommun({
							phone: contact.phone,
							infoId: contact.info.id || contact.info.askrentId || contact.info
								.buystoreId,
							type: contact.info.id ? 0 : (contact.info.askrentId ? 1 : 2),
						}).then(res => {})
					}
				});
			},
			getCurrentUser(callback){
					getUserInfo().then(res => {
						let d = {
							phone: res.data.phone,
							username: res.data.nickname,
							open: 1,
							contactPhone: res.data.phone,
							contactName: res.data.nickname,
						};
						contactAdd(d).then(r => {
							
							d.contactId = r.data.id;
							d.contactName = r.data.username;
							d.username = r.data.username;
							d.id = r.data.id;
							d.were = r.data.were;
							d.type = r.data.type;
							callback&&callback(d);
						}).catch(e=>{
							// this.isToAdd = false;
						})
					})
			},
			//初始化当前联系人
			initContact() {
				if(timeOut){
					clearTimeout(timeOut);
					timeOut = null;
				}
				
				if(this.isToAdd){
					return;	
				}
				timeOut = setTimeout(()=>{
					this.isToAdd = true;
					const curUserInfo = uni.getStorageSync('curUserInfo');
					console.log("curUserInfo",curUserInfo)
					if(curUserInfo){
						uni.$emit("initContact", JSON.parse(curUserInfo))
						this.isToAdd = false;
						return;
					}
					this.getCurrentUser(data=>{
						this.isToAdd = false;
						uni.$emit("initContact", data)
					})
				},1500)
				
			},
			onLoginSuccess: function(myName) {
				// uni.hideLoading();
				// uni.redirectTo({
				// 	url: "../conversation/conversation?myName=" + myName,
				// });
			},
			share() {
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 5,
					href: "http://uniapp.dcloud.io/",
					title: "uni-app分享",
					summary: "我正在使用HBuilderX开发uni-app，赶紧跟我一起来体验！",
					imageUrl: "https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni@2x.png",
					success: function(res) {
						
					},
					fail: function(err) {
						
					}
				});

			},
			/*********************关于收藏************************/
			existsIsLove(d) {
				
				return new Promise((reslove, reject) => {
					existsCollect({
						collectId: d.id,
						type: d.type
					}).then(res => {
						
						if (res.code == 200) {
							reslove(res.data.list.length > 0 ? true : false);
						}
					}).catch(e => {
						reject(e)
					})
				})

			},
			toCollect(d, callback) {
				
				let that = this;
				try {
					let res;
					if (!d.status) {
						uni.showModal({
							title: '提示',
							content: '你确定取消吗',
							success: function(res) {
								if (res.confirm) {
									delCollect({
										type: d.type,
										collectId: d.id
									}).then(res => {
										
										if (res.code == 200) {
											callback && callback({
												success: true,
												id: d.id
											})
										}
									})
								}

							}
						});
					} else {
						
						addCollect({
							type: d.type,
							collectId: d.id,
							friendId: d.uid,
							title: d.title,
							storeCategory: d.storeCategory
						}).then(res => {
							
							if (res.code == 200) {
								callback && callback({
									success: true,
									id: d.id
								})
							}
						})
					}

				} catch (e) {
					//TODO handle the exception
				}

			},
			/*********************关于收藏************************/
			getUserInfo(cb) {
				var me = this;

				if (this.userInfo) {
					typeof cb == "function" && cb(this.userInfo);
				} else {
					// 调用登录接口
					uni.login({
						success() {
							uni.getUserInfo({
								success(res) {
									me.userInfo = res.userInfo;
									typeof cb == "function" && cb(me.userInfo);
								},
							});
						},
					});
				}
			},
			checkIsIPhoneX: function() {
				const me = this;
				uni.getSystemInfo({
					success: function(res) {
						// 根据 model 进行判断
						if (res.model && res.model.search("iPhone X") != -1) {
							me.isIPX = true;
						}
					},
				});
			},
		},

		// getPage(pageName){
		// 	var pages = getCurrentPages();
		// 	return pages.find(function(page){
		// 		return page.__route__ == pageName;
		// 	});
		// },
		onLaunch(option) {
			uni.hideTabBar()
			let that = this;
			
			if (option.query.spread) that.globalData.spread = option.query.spread;
			if (option.query.infoId) that.globalData.infoId = option.query.infoId;
			if (option.query.spreadType) that.globalData.spreadType = option.query.spreadType;
			if (option.query.storeCategory) that.globalData.storeCategory = option.query.storeCategory;
			if (option.query.st) that.globalData.st = option.query.st;
			// 加载获取经纬度城市
			this.$reLocation(() => {

			})



			// 主题变色
			getTheme().then(resP => {
				that.$Cache.set('theme', `theme${Number(resP.data.value)}`);
				that.globalData.theme = that.$Cache.get('theme')
				// #ifdef H5
				window.document.documentElement.setAttribute('data-theme', that.globalData.theme);
				// #endif
			})
			// #ifdef APP-PLUS || H5
			uni.getSystemInfo({
				success: function(res) {
					// 首页没有title获取的整个页面的高度，里面的页面有原生标题要减掉就是视口的高度  
					// 状态栏是动态的可以拿到 标题栏是固定写死的是44px
					let height = res.windowHeight - res.statusBarHeight - 44;
					// #ifdef H5 || APP-PLUS
					that.globalData.windowHeight = res.windowHeight + 'px';
					// #endif
					that.$store.commit('SYSTEM_PLATFORM', res.platform.toLowerCase());
				}
			});
			// #endif	

			// #ifdef MP
			if (option.query.hasOwnProperty('scene')) {
				switch (option.scene) {
					case 1047: //扫描小程序码
					case 1048: //长按图片识别小程序码
					case 1049: //手机相册选取小程序码
					case 1001: //直接进入小程序
						let value = this.$util.getUrlParams(decodeURIComponent(option.query.scene));
						that.globalData = this.$util.formatMpQrCodeData(value);
						break;
				}
			}
			if (option.spread) that.globalData.spread = option.spread;
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			that.globalData.navH = menuButtonInfo.top * 2 + menuButtonInfo.height / 2;
			const updateManager = uni.getUpdateManager();
			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
				if (res.hasUpdate) {
					updateManager.onUpdateReady(function(res2) {
						uni.showModal({
							title: '更新提示',
							content: '发现新版本，是否重启应用?',
							cancelColor: '#eeeeee',
							confirmColor: '#FF0000',
							success(res2) {
								if (res2.confirm) {
									// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
									updateManager.applyUpdate();
								}
							}
						});
					});
				}
			});

			updateManager.onUpdateFailed(function(res) {
				// 新的版本下载失败
				uni.showModal({
					title: '提示',
					content: '检查到有新版本，但下载失败，请检查网络设置',
					success(res) {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});
			});

			if (HTTP_REQUEST_URL == '') {
				console.error(
					"请配置根目录下的config.js文件中的 'HTTP_REQUEST_URL'\n\n请修改开发者工具中【详情】->【AppID】改为自己的Appid\n\n请前往后台【小程序】->【小程序配置】填写自己的 appId and AppSecret"
				);
				return false;
			}
			// #endif
			// 获取导航高度；
			uni.getSystemInfo({
				success: function(res) {
					that.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 91;
					that.globalData.navHeight2 = res.statusBarHeight * (750 / res.windowWidth);
					// that.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth)
				}
			});

			// #ifdef H5	
			if (option.query.hasOwnProperty('type') && option.query.type == "iframeVisualizing") {
				this.globalData.isIframe = true;
			} else {
				this.globalData.isIframe = false;
			}

			let snsapiBase = 'snsapi_base';
			let urlData = location.pathname + location.search;
			if (!that.$store.getters.isLogin && Auth.isWeixin()) {
				const {
					code,
					state,
					scope
				} = option.query;
				if (code && code != uni.getStorageSync('snsapiCode') && location.pathname.indexOf(
						'/pages/users/wechat_login/index') === -1) {
					// 存储静默授权code
					uni.setStorageSync('snsapiCode', code);
					let spread = that.globalData.spread ? that.globalData.spread : 0;
					Auth.auth(code, that.$Cache.get('spread'))
						.then(res => {
							uni.setStorageSync('snRouter', decodeURIComponent(decodeURIComponent(option.query
								.back_url)));
							if (res.type === 'register') {
								this.$Cache.set('snsapiKey', res.key);
							}
							if (res.type === 'login') {
								this.$store.commit('LOGIN', {
									token: res.token
								});
								this.$store.commit("SETUID", res.id);
								location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
							}
						})
						.catch(error => {
							if (!this.$Cache.has('snsapiKey')) {
								if (location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
									Auth.oAuth(snsapiBase, option.query.back_url);
								}
							}
						});
				} else {
					if (!this.$Cache.has('snsapiKey')) {
						if (location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
							Auth.oAuth(snsapiBase, urlData);
						}
					}
				}
			} else {
				if (option.query.back_url) {
					location.replace(uni.getStorageSync('snRouter'));
				}
			}
			// #endif

			// #ifdef MP
			// 小程序静默授权
			// if (!this.$store.getters.isLogin) {
			// 	Routine.getCode().then(code => {
			// 			let userInfo = {
			// 				code: code,
			// 				spreadPid: this.globalData.spread, //获取推广人ID
			// 				type: 'routine'
			// 			};
			// 			Routine.authUserInfo(userInfo)
			// 		})
			// 		.catch(res => {
			// 			uni.hideLoading();
			// 		});
			// }
			// #endif
			this.$store.commit('GLOBAL_DATA', that.globalData);
			if (this.$store.getters.isLogin && this.globalData.spread) {
				spread(this.globalData.spread).then(res => {}).catch(res => {})
			}
			// 调用 API 从本地缓存中获取数据
			// uni.setInnerAudioOption({
			//   obeyMuteSwitch: false
			// });
			var me = this;
			var logs = uni.getStorageSync("logs") || [];
			logs.unshift(Date.now());
			uni.setStorageSync("logs", logs);

			disp.on("em.main.ready", function() {
				calcUnReadSpot();
			});
			disp.on("em.chatroom.leave", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.session.remove", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.audio.fileLoaded", function() {
				calcUnReadSpot();
			});
			disp.on("em.main.deleteFriend", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.audio.fileLoaded", function() {
				calcUnReadSpot();
			}); //
			disp.on("em.mian.profile.update", function() {
				me.fetchUserInfoWithLoginId()
			});
			disp.on("em.mian.friendProfile.update", function() {
				me.fetchFriendInfoFromServer()
			});
			WebIM.conn.listen({
				onOpened(message) {
					
					if (
						getCurrentRoute() == "pages/users/login/index"
					) {
						me.globalData.onLoginSuccess(
							uni.getStorageSync("myUsername").toLowerCase()
						);
					}
				},

				onReconnect() {
					uni.showToast({
						title: "重连中...",
						duration: 2000,
					});
				},

				onSocketConnected() {
					uni.showToast({
						title: "socket连接成功",
						duration: 2000,
					});
				},

				onClosed() {
					uni.showToast({
						title: "退出登录",
						icon: "none",
						duration: 2000,
					});
					// uni.redirectTo({
					// 	url: "/pages/users/login/index",
					// });
					me.globalData.conn.closed = true;
					WebIM.conn.close();
					// uni.removeStorageSync('pushStorageData');
					// uni.clearStorageSync();
				},

				onInviteMessage(message) {
					me.globalData.saveGroupInvitedList.push(message);
					disp.fire("em.invite.joingroup", message); // uni.showModal({
					// 	title: message.from + " 已邀你入群 " + message.roomid,
					// 	success(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	},
					// 	error(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	}
					// });
				},

				onReadMessage(message) {
					
				},

				//onPresence为旧版 ，建议参考最新增删好友api文档 ：http://docs-im.easemob.com/im/web/basics/buddy
				onPresence(message) {
					switch (message.type) {
						case "unsubscribe":
							break;
							// 好友邀请列表
						case "subscribe":
							for (let i = 0; i < me.globalData.saveFriendList.length; i++) {
								if (me.globalData.saveFriendList[i].from === message.from) {
									me.globalData.saveFriendList[i] = message;
									disp.fire("em.subscribe");
									return;
								}
							}
							msgStorage.saveReceiveMsg(message, "INFORM"); //存添加好友消息，方便展示通知
							me.globalData.saveFriendList.push(message);
							disp.fire("em.subscribe");

							break;

						case "subscribed":
							uni.showToast({
								title: "添加成功",
								duration: 1000,
							});
							disp.fire("em.subscribed");
							break;

						case "unsubscribed":
							disp.fire("em.unsubscribed", message);
							break;
						case "direct_joined":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "memberJoinPublicGroupSuccess":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "invite":
							// 防止重复添加
							for (
								let i = 0; i < me.globalData.saveGroupInvitedList.length; i++
							) {
								if (me.globalData.saveGroupInvitedList[i].from === message.from) {
									me.globalData.saveGroupInvitedList[i] = message;
									disp.fire("em.invite.joingroup");
									return;
								}
							}
							me.globalData.saveGroupInvitedList.push(message);
							msgStorage.saveReceiveMsg(message, "INFORM"); //存添加好友消息，方便展示通知
							disp.fire("em.invite.joingroup");
							break;
						case "unavailable":
							disp.fire("em.contacts.remove");
							disp.fire("em.group.leaveGroup", message);
							break;

						case "deleteGroupChat":
							disp.fire("em.invite.deleteGroup", message);
							break;

						case "leaveGroup":
							disp.fire("em.group.leaveGroup", message);
							break;

						case "removedFromGroup":
							disp.fire("em.group.leaveGroup", message);
							break;

						default:
							break;
					}
				},

				onRoster(message) {
					// let pages = getCurrentPages();
					// if(pages[0]){
					// 	pages[0].onShow();
					// }
				},

				onVideoMessage(message) {
					

					if (message) {
						msgStorage.saveReceiveMsg(message, msgType.VIDEO);
					}

					calcUnReadSpot(message);
					ack(message);
					onGetSilentConfig(message);
				},

				onAudioMessage(message) {
					

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.AUDIO);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onCmdMessage(message) {
					

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.CMD);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				// onLocationMessage(message){
				// 	console.log("Location message: ", message);
				// 	if(message){
				// 		msgStorage.saveReceiveMsg(message, msgType.LOCATION);
				// 	}
				// },
				onTextMessage(message) {
					

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.TEXT);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onEmojiMessage(message) {
					

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.EMOJI);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onPictureMessage(message) {
					

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.IMAGE);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				onFileMessage(message) {
					

					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.FILE);
						}

						calcUnReadSpot(message);
						ack(message);
						onGetSilentConfig(message);
					}
				},

				// 各种异常
				onError(error) {
					console.log(error); // 16: server-side close the websocket connection
					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
					//   // if(error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED && !logout){
					//   // if(WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax){
					//   // 	return;
					//   // }
					//   uni.showToast({
					//     title: "websocket 断开",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					//   logout = true;
					//   return;
					// } // 8: offline by multi login

					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
					//   uni.showToast({
					//     title: "offline by multi login",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					// }

					if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.passwordErr"); // uni.showModal({
						// 	title: "用户名或密码错误",
						// 	confirmText: "OK",
						// 	showCancel: false
						// });
					}

					if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.tokenErr");
					}

					if (error.type == "socket_error") {
						///sendMsgError
						
						uni.showToast({
							title: "网络已断开",
							icon: "none",
							duration: 2000,
						});
						disp.fire("em.error.sendMsgErr", error);
					}
				},
			});
			this.globalData.checkIsIPhoneX();
			this.tokenLogin();
		},

		methods: {
			async fetchUserInfoWithLoginId() {
				const userId = await uni.WebIM.conn.user;
				if (userId) {
					try {
						const {
							data
						} = await uni.WebIM.conn.fetchUserInfoById(userId)
						this.globalData.userInfoFromServer = Object.assign({}, data[userId]);
					} catch (error) {
						
						uni.showToast({
							title: "用户属性获取失败",
							icon: "none",
							duration: 2000,
						})
					}

				}
			},
			async fetchFriendInfoFromServer() {
				let friendList = []
				try {
					const res = await uni.WebIM.conn.getContacts()
					friendList = Object.assign([], res?.data)
					if (friendList.length && friendList.length < 99) {
						const {
							data
						} = await uni.WebIM.conn.fetchUserInfoById(friendList)
						this.setFriendUserInfotoMap(data)
					} else {
						let newArr = _chunkArr(friendList, 99)
						for (let i = 0; i < newArr.length; i++) {
							const {
								data
							} = await uni.WebIM.conn.fetchUserInfoById(newArr[i])
							this.setFriendUserInfotoMap(data)
						}
					}
				} catch (error) {
					
					uni.showToast({
						title: "用户属性获取失败",
						icon: "none"
					})
				}

			},
			setFriendUserInfotoMap(data) {
				if (Object.keys(data).length) {
					for (const key in data) {
						if (Object.hasOwnProperty.call(data, key)) {
							const values = data[key];
							Object.values(values).length && this.globalData.friendUserInfoMap.set(key, values);
						}
					}
				}
			},
			async toImLogin() {
				getIm().then(result => {
					
					WebIM.conn.open({
						appKey: WebIM.config.appkey,
						user: result.data.username,
						pwd: '123456',
						success: function(res) {
							var imToken = res.access_token
							uni.setStorage({
								key: "imToken",
								data: imToken
							});
							uni.setStorage({
								key: "myUsername",
								data: res.user.username
							});
						},
						error: function(r) {
							
						}
					});
				})
			},
			tokenLogin() {
				let imToken = '';
				let username = '';
				uni.getStorage({
					key: 'imToken',
					success(res) {
						imToken = res.data;
						
					}
				})
				uni.getStorage({
					key: 'myUsername',
					success(res) {
						username = res.data;
						
					}
				})
				
				if (imToken) {
					var options = {
						appKey: WebIM.config.appkey,
						user: username,
						accessToken: imToken
					};
					WebIM.conn.open(options);
				} else {
					this.toImLogin()
				}

			},
			toSpread(option) {
				if (option.query.path && option.query.infoId) {
					uni.switchTab({
						url: "/" + option.path,
						success() {
							uni.navigateTo({
								url: option.query.path + "?id=" + option.query.infoId + "&spread=" + option
									.query.spread+'&storeCategory='+option.query.storeCategory+'&st='+option.query.st
							})

						}
					});
				}
				
			}
		},
		onShow: function(e) {
			
			this.$nextTick(() => {
				this.toSpread(e);
			})

			// #ifdef H5
			uni.getSystemInfo({
				success(e) {
					/* 窗口宽度大于420px且不在PC页面且不在移动设备时跳转至 PC.html 页面 */
					if (e.windowWidth > 420 && !window.top.isPC && !/iOS|Android/i.test(e.system)) {
						// window.location.pathname = 'https://java.crmeb.net/';
						/* 若你的项目未设置根目录（默认为 / 时），则使用下方代码 */
						window.location.pathname = '/static/html/pc.html';
					}
				}
			})
			// #endif
		},
		onHide: function() {}
	};
</script>
<style lang="scss">
	@import "@/plugin/animate/animate.min.css";
	@import 'static/css/base.css';
	@import 'static/iconfont/iconfont.css';
	@import 'static/css/guildford.css';
	// @import url("https://image.shanghepu.com/cdn/css/guildford.wxss");
	@import 'static/css/style.scss';
	// @import 'static/css/releaseForm.css';

	@import "@/subpackageuni/uview-ui/index.scss";

	/* 条件编译，仅在H5平台生效 */
	// #ifdef H5
	body::-webkit-scrollbar,
	html::-webkit-scrollbar {
		display: none;
	}

	// #endif
	*,
	view,
	input,
	text,
	textarea,
	button {
		box-sizing: border-box;
	}

	.bg-color-red {
		background-color: #E93323;
	}

	.syspadding {
		padding-top: var(--status-bar-height);
	}

	.flex {
		display: flex;
	}

	.uni-scroll-view::-webkit-scrollbar {
		/* 隐藏滚动条，但依旧具备可以滚动的功能 */
		display: none
	}

	::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	.uni-p-b-98 {
		height: 150rpx;
		/* 兼容 IOS<11.2 */
		height: calc(150rpx + constant(safe-area-inset-bottom));
		/* 兼容 IOS>11.2 */
		height: calc(150rpx + env(safe-area-inset-bottom));
	}
</style>